<template>
  <el-card class="login-card">
    <div slot="header" class="login-header">
      <h2>用户登录</h2>
    </div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="rules"
      label-width="80px"
      @keyup.enter="handleLogin"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          @keyup.enter.native="handleLogin"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          @keyup.enter.native="handleLogin"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
        <el-button @click="resetForm('loginForm')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <span>还没有账号？</span>
        <el-button type="text" @click="$router.push('/auth/register')"
          >立即注册</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        loginForm: {
          username: "",
          password: "",
        },
        rules: {
          username: [
            { required: true, message: "请输入用户名", trigger: "blur" },
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "blur" },
          ],
        },
      };
    },
    methods: {
      async handleLogin() {
        this.$refs.loginForm.validate(async (valid) => {
          if (valid) {
            try {
              const response = await this.$axios.post(
                "/auth/login",
                this.loginForm
              );
              const { token } = response.data;
              const { ...userInfo } = response.data.data;
              // console.log("-------------------");
              // console.log("res: ", response);
              // console.log("token:", token, "userInfo:", userInfo);
              if (token && userInfo) {
                // 保存token和用户信息
                // localStorage.setItem("token", token);
                // localStorage.setItem("user", JSON.stringify(response.data));
                this.$store.dispatch("login", { token, userInfo });

                this.$message.success({
                  message: "登录成功",
                  type: "success",
                  duration: 200,
                });

                // 根据用户角色跳转不同页面
                if (response.data.role === "admin") {
                  this.$router.push("/dashboard");
                } else {
                  this.$router.push("/blogs");
                }
              } else {
                this.$message.error("登录失败，请检查用户名和密码");
              }
            } catch (error) {
              this.$message.error(
                error.response?.data?.message || "登录失败，请检查用户名和密码"
              );
            }
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    },
  };
</script>

<style scoped>
  .login-card {
    max-width: 400px;
    margin: 100px auto;
  }

  .login-header {
    text-align: center;
  }
</style>
